export const Storage = {
  set: (key, value, expire) => {
    const obj = {
      data: value,
      time: Date.now(),
      expire: expire
    }
    localStorage.setItem(key, JSON.stringify(obj))
  },
  get: key => {
    let val = localStorage.getItem(key)
    if (!val) {
      return null
    }
    val = JSON.parse(val)
    if (Date.now() - val.time > val.expire * 1000) {
      localStorage.removeItem(key)
      return null
    }
    return val.data
  },
  del: key => {
    localStorage.removeItem(key)
  }
}

// 时间格式化
export function formatDate (time) {
  const dateTime = new Date(time * 1000)
  const year = dateTime.getFullYear()
  let month = dateTime.getMonth() + 1
  month = month < 10 ? '0' + month : month
  let date = dateTime.getDate()
  date = date < 10 ? '0' + date : date
  let hour = dateTime.getHours()
  hour = hour < 10 ? '0' + hour : hour
  let minute = dateTime.getMinutes()
  minute = minute < 10 ? '0' + minute : minute
  let second = dateTime.getSeconds()
  second = second < 10 ? '0' + second : second
  return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
}

// 日期格式化
export function formatOnlyDate () {
  const dateTime = new Date()
  const year = dateTime.getFullYear()
  let month = dateTime.getMonth() + 1
  month = month < 10 ? '0' + month : month
  let date = dateTime.getDate()
  date = date < 10 ? '0' + date : date
  return year + '-' + month + '-' + date
}
